# -*- coding: utf-8 -*-
import werkzeug.utils
from odoo import http
from odoo.http import request

from .. import redis_factory

class AuthLogin(http.Controller):

    @http.route('/auth/login', type='http', auth="none")
    def auth_login(self, token, redirect=None):
        if not token:
            return werkzeug.utils.redirect('/web/login', 303)

        pool = redis_factory.RedisPoolConnection()
        uid = pool.get(token)
        pool.delete(token)
        if not uid:
            return werkzeug.utils.redirect('/web/login', 303)

        uid = int(uid)

        user = request.env['res.users'].sudo().browse(uid)
        if not user:
            return werkzeug.utils.redirect('/web/login', 303)

        user._update_last_login()

        request.uid = uid
        request.params['login_success'] = True
        request.disable_db = False

        request.session['db'] = request.session.db
        request.session['login'] = user.login
        request.session['uid'] = uid
        request.session.get_context()
        request.session['session_token'] = user._compute_session_token(request.session.sid)

        # request.session['should_save'] = True
        request.session['rotate'] = True

        return http.redirect_with_hash("/web" if not redirect else redirect)